/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<!-- 单视频播放组件 -->
  <div class="flvplayer" v-if="!!curVideoInfo">
    <div class="flv-header">
      <span class="title">{{ this.Title || title }}</span>
      <span class="list-icon">
        <div>
          <i class="iconfont icon-shipinshuaxin" ref="videoRefresh" @click="reload(curVideoInfo.flvPlayer)"></i>
        </div>
        <slot name="vediolist"></slot>
      </span>
    </div>
    <div class="flv-content">
      <video autoplay controls :width="Width" :height="Height" :id='"videoElement" + curVideoInfo.id'></video>
    </div>
  </div>
</template>

<script>
import flvjs from 'flv.js'

export default {
  name: 'flvplayer',
  props: {
    curVideoInfo: { // 当前播放的视频信息
      type: Object
    },
    Width: {
      type: String,
      default: '100%'
    },
    Height: {
      type: String,
      default: '237'
    },
    Title: { // 播放窗口的标题，如果不传，默认是视频信息里name
      type: String
    },
    autoPlay: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      playPromise: null,
      timer: 0,
      reloadTimer: 0,
      title: this.Title
    }
  },
  mounted () {
    if (!this.curVideoInfo || this.curVideoInfo === {}) return
    if (this.curVideoInfo.hasOwnProperty('name')) {
      this.title = this.curVideoInfo.name
    }
    this.$nextTick(() => {
      this.createVideo()

      // setInterval(() => {
      //   // console.log(this.player)
      //   try {
      //     if (this.player && this.player.buffered && this.player.buffered.length) {
      //       let end = this.player.buffered.end(0)// 获取当前buffered值
      //       let diff = end - this.player.currentTime// 获取buffered与currentTime的差值
      //       if (diff >= 0.5) { // 如果差值大于等于0.5 手动跳帧 这里可根据自身需求来定
      //         this.player.currentTime = this.player.buffered.end(0) - 0.5// 手动跳帧
      //         // this.player.pause()
      //         this.player.unload()
      //         this.player.load()
      //         this.player.play()
      //       }
      //       this.player.unload()
      //       this.player.load()
      //       this.player.play()
      //     }
      //   } catch (error) {
      //     console.log('catch error:', error)
      //     console.log('this.player:', this.player)
      //     this.reload(this.player)
      //   }
      // }, 2 * 1000) // 2000毫秒执行一次
      let _this = this
      this.reloadTimer = setTimeout(() => {
        this.player.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
          console.log('errorType:', errorType)
          console.log('errorDetail:', errorDetail)
          console.log('errorInfo:', errorInfo)
          // 视频出错后销毁重新创建
          let dom = _this.$refs.videoRefresh
          dom && dom.click()
        })

        _this.player.on('statistics_info', function (res) {
          console.log('statistics_info:', res)
          let dom = _this.$refs.videoRefresh
          dom && dom.click()
        })
      }, 2000)
    })
  },
  watch: {
    curVideoInfo: {
      handler: function (val) {
        if (!val) return
        if (val.hasOwnProperty('name')) {
          this.title = val.name
        }
      },
      deep: true
    }
  },
  methods: {
    createVideo () {
      if (flvjs.isSupported()) {
        if (!this.curVideoInfo) return
        this.curVideoInfo.videoElement = document.getElementById(`videoElement${this.curVideoInfo.id}`)
        let flvPlayer = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          url: this.curVideoInfo.url
        },
        {
        //   lazyLoadMaxDuration: 5 * 60
          // enableWorker: true, // 启用分离的线程进行转换
          // enableStashBuffer: false, // 关闭IO隐藏缓冲区
          stashInitialSize: 128 // 减少首帧显示等待时长
        }
        )
        this.player = flvPlayer
        this.curVideoInfo.flvPlayer = flvPlayer
        flvPlayer.attachMediaElement(this.curVideoInfo.videoElement)
        this.timer = setTimeout(() => {
          flvPlayer.load()
          if (this.autoPlay) {
            flvPlayer.play() // 播放
          } else {
            flvPlayer.pause()
          }
        }, 1 * 1000)
      }
    },
    play (media) {
      // 播放
      media.play()
    },
    reload (media) {
      console.log('reload media:', this.curVideoInfo)
      // 重新加载监控视频（以当前时间为准）
      this.flv_destroy(media)
      this.createVideo()
    },
    flv_pause (media) {
      // 暂停
      media.pause()
    },
    flv_destroy (media) {
      // 销毁
      if (media) {
        // media.pause()
        media.unload()
        media.detachMediaElement()
        media.destroy()
        media = null
      }
    }
  },
  destroyed () {
    clearTimeout(this.timer)
    clearTimeout(this.reloadTimer)
    if (!this.curVideoInfo) return
    this.flv_destroy(this.curVideoInfo.flvPlayer)
  }
}
</script>
